<?php
/**
 * Author  : DAMMAK Wassim
 * Contact : wdammak@talend.com
 * Date    : 12/2008
 * @copyright talend.com 2008
 * @license GNU/GPL Version 2
 **/ 
$maintenance=false;
$nb_occur=3000000;
$time_start = microtime(true);

if($_SERVER['HTTP_HOST'] == "localhost" ){
	set_include_path(".;". dirname(__FILE__).DIRECTORY_SEPARATOR."lib;". get_include_path() ); //LOCAL 
}else{ 
	set_include_path(DIRECTORY_SEPARATOR. dirname(__FILE__).DIRECTORY_SEPARATOR.'lib'.PATH_SEPARATOR.get_include_path());
}
require_once "lib/Zend/Loader.php";

Zend_Loader::loadClass("Zend_Auth");
Zend_Loader::loadClass("Zend_Auth_Result");
Zend_Loader::loadClass("Zend_Auth_Adapter_Interface");

Zend_Loader::loadClass("Zend_Acl");
Zend_Loader::loadClass("Zend_Acl_Role");
Zend_Loader::loadClass("Zend_Acl_Resource");

Zend_Loader::loadClass("Zend_Db");
Zend_Loader::loadClass("Zend_Registry");
Zend_Loader::loadClass("Exception");

require_once "lib/Zend/Db/Adapter/Pdo/Mysql.php";
require_once "lib/Zend/Auth/Storage/Session.php" ;
require_once "lib/Zend/Auth.php" ; 
require_once "lib/Zend/Http/Client.php";
require_once "includes/configure.php";
require_once "lib/babili/Authentification.php";
require_once "includes/languages/english.php";
require_once "includes/MyAcl.php";
require_once "includes/cryptage.php";

//include(PUN_ROOT."include/function_contact.php");


$db = new Zend_Db_Adapter_Pdo_Mysql( array(
	'host'     => DB_SERVEUR,
	'username' => DB_USER,
	'password' => DB_PASS,
	'dbname'   => DB_BDD
));
$db->query('SET NAMES UTF8');	
$db->query('SET CHARACTER SET utf8');
$auth  =  Zend_Auth :: getInstance ( ) ;
$db->setFetchMode(Zend_Db::FETCH_OBJ);

 /*if(isset($_GET['option']) && $_GET['option']=="registration"){
	if(isset($_GET['task'])) 
		header("Location: register.php?task=".$_GET['task']);
	else header("Location: register.php");
 }*/

 if($auth -> hasIdentity() && isset($_GET["action"]) && $_GET["action"]=="logout") {	 
		$auth -> clearIdentity () ;
		unset($_SESSION['gid'],$_SESSION['languages'],$_SESSION['langues'],$_SESSION['refLang'],$_SESSION['refTag'],$_SESSION['selectShow'],$_SESSION['keys'],$_SESSION['listUsers'],$_SESSION['ln_browser'],$_SESSION['groupe'],$_SESSION['textShow'],$_SESSION['browser']);
		//header("Location: ".$_SERVER["SCRIPT_NAME"]);
 }

/*************************************************
//Get All Projects
*************************************************/
$selectProjects = $db->select()
  ->from('projets',array('*'))
  ->join('keys','keys.id_projet=projets.id_projet','count(keys.id_key) as Total')
  ->where('status=1')
  ->group('projets.id_projet')
;
$resultProjects = $db->fetchAll($selectProjects);

/*************************************************
//Get All langues
*************************************************/
//unset($_SESSION['languages']);
if(!isset($_SESSION['languages'])){
	$selectLangues = $db->select()->from('languages',array('*'))
						->where('languages.status=1');	
	$resultLangues = $db->fetchAll($selectLangues);
	$_SESSION['languages']=$resultLangues;
}else{
	$resultLangues=$_SESSION['languages'];
}


$codeAuth="";
// Vrifier si je suis identifi	
  if ( !$auth -> hasIdentity ( ) ){      	
	if(isset($_POST['username']) ){
 		// Automatically load class Zend_Db_Adapter_Pdo_Mysql and create an instance of it.		
		 $myAdapter = new Authentification($db);		
		 $myAdapter->setIdentity($_POST['username'])
			  ->setCredential(talend_crypt($_POST['passwd']));		  
		 $result  =  $auth -> authenticate ($myAdapter) ;

		 if ($result->isValid()) {
		 	$_SESSION['project']=$_POST['project'];
			foreach($resultProjects as $project){
				if($_SESSION['project']==$project->id_projet){
					$_SESSION['projectName']=trim($project->name);
				}
			}
	 	 	// VUE				
			//header("Location:".$_SERVER["SCRIPT_NAME"]);			
			//require_once("includes/main.php");
			$codeAuth=1;
			unset($_SESSION['keys']);
		 }else {
		 	$selectUser = $db->select()->from('users',array('*'))
							->where('email= ? ',$_POST['username']);
			$resultUser = $db->fetchAll($selectUser);
			//Creation d'un nouveau utilisateur
		 	 if(count($resultUser)==0){	
			 	$rows = array (
					'email'    => $_POST['username'],
					'password' => talend_crypt($_POST['passwd']),
					'gid' =>'0',
					'register_date' => date("Y-m-d H:i:s"),
					'active' =>'1',
				);
				mail($_POST['username'],"Babili new account","Hi,\n\n"."Thank you for taking part in the Babili project!\nHere are your details to connect to Babili - the Talend Community translation application:\nLogin: ".$_POST['username']."\nPassword: ".$_POST['passwd']."\n\nSincerely,\nThe Talend Translation Team\n","From: Talend - Babili <babili@talend.com>\r\n");
	
				$table = 'users';				
				$affectedRows = $db->insert($table, $rows);	
				mysql_connect(DB_SERVEUR,DB_USER,DB_PASS);
				//contact($_POST['username'],'babili');
				//require_once("includes/main.php");
				
				// Automatically load class Zend_Db_Adapter_Pdo_Mysql and create an instance of it.		
				 $myAdapter = new Authentification($db);		
				 $myAdapter->setIdentity($_POST['username'])
					  ->setCredential(talend_crypt($_POST['passwd']));		  
				 $result  =  $auth -> authenticate ($myAdapter) ;
		 
				$codeAuth=1;
				
			 }else{//Envoie d'email avec les information d'utilisateur.
			 	mail($_POST['username'],"Babili Password","Hi,\n\n"."It looks like you lost your password? :-) Here are your details to connect to Babili - the Talend Community translation application:\nLogin: \n".$_POST['username']."\nPassword: ".
	talend_decrypt(current($resultUser)->password)."\n\nSincerely,\nThe Talend Translation Team\n","From: Talend - Babili <babili@talend.com>\r\n");
				$codeAuth=22;
				//header("Location: ".$_SERVER["SCRIPT_NAME"]."?message=wrong_login_or_pass");							
			}
			
		 }	 		 
	//Non identifi
	//=>afficher le formulaire d'identification	 
	}else{
		$codeAuth=3;
		/*require_once "includes/statistics.php";		
		require_once "includes/auth.php";*/
	}
 }else{//dja identifi
	//require_once("includes/main.php");
	$codeAuth=1;	
 }

 if(!isset($_COOKIE['guidelines'])){
 	setcookie("guidelines","yes",time()+(3600*24*30),'/');
	$is_visible_guidelines=true;
 }else{
	$is_visible_guidelines=false;
 }
 
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Made By D.Wassim : wdammak@talend.com -->
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Talend Babili<?php if($codeAuth==1): ?> / Project: <?php echo $_SESSION['projectName']; ?><?php endif;?></title>
	<meta name="description" content="With Talend Babili, Community members can translate the user interface of Talend's products in any language." />
	<meta name="Author" content="Wassim DAMMAK">
	
	<link rel="stylesheet" href="css/general.css" type="text/css" />
	<?php if($codeAuth!=1): ?>
		<link rel="stylesheet" href="css/cd_login.css" type="text/css" />
	<?php else: ?>
		<?php 
		/*
		<link rel="stylesheet" href="css/screen.css" />
		*/ ?>
	<?php endif; ?>
		
	<script type="text/javascript" src="js/trans.js"></script>
</head>
<body style="position:relative;">
<div id="page" style="display:block;">	
	<div id="cacherTout" class="cachediv">&nbsp;
		<!--[if lte IE 6.5]><iframe></iframe><![endif]-->
	</div>
	<?php 
		/**
			<div id="navcol">
				<?php require_once("includes/navleft.php"); ?>    
			</div>	
	
			<div id="sidecol">
				<?php require_once("includes/navright.php"); ?>
			</div>
		**/
	?>	
	<!--Maintenance-->
	<?php if($maintenance==true): ?>
	 	
		<div id="header">		
			<?php include("includes/header.php");  ?> 
		</div>
		
		<div id="main">	
	 		<div class="maintenance">
				<img src="http://www.talend.com/img/style/logo-sources.jpg" align="left" style="padding:10px;" />
				The Babili site is temporarily unavailable for maintenance.<br />
				We are sorry for the inconvenience caused, but please dont hesitate to come back later!<br/><br/>
				The babili team
			</div>
			<?php 
				$codeAuth=2;
				$auth -> clearIdentity () ;
				unset($_SESSION['gid'],$_SESSION['langues'],$_SESSION['refLang'],$_SESSION['refTag']);	
			?>
		</div>
		
	<?php else: ?>

		<?php if($codeAuth==1): ?>
			
		 	<div id="header">		
				<?php 
					require_once("includes/languages/default.php");
					require_once("includes/helper.php");
					require_once("includes/header.php"); 
				?> 
			</div>
			<div id="main">	
				<?php 
				    require_once("includes/main.php");
				    require_once "includes/boards.php";
                ?>
   	 		</div>
			
		 <?php else:?>
		 
		 	<div id="header">		
				<?php include("includes/header.php");  ?> 
			</div>
			<div id="main">	
				<?php
				 // afficher les messages d'erreur
				 if ($codeAuth==2) {
					echo "<center><strong>Wrong login or pass!</strong></center><br/>";
				 }
				 
				  // afficher les messages d'erreur
				 if ($codeAuth==22) {
					echo "<center><strong><span style=\"font-size:16px; color:#FFDF00;\">Wrong password!<br/>We'll send your password to your email address in a few seconds.</span></strong></center><br/>";
				 }
				 if(!isset($_GET["action"]) || (isset($_GET["action"]) && $_GET["action"]!="logout")){
					 unset($_SESSION['gid'],$_SESSION['languages'],$_SESSION['langues'],$_SESSION['refLang'],$_SESSION['refTag'],$_SESSION['selectShow'],$_SESSION['keys'],$_SESSION['listUsers'],$_SESSION['ln_browser'],$_SESSION['groupe'],$_SESSION['textShow'],$_SESSION['browser']);
				 }
				 require_once "includes/auth.php";
				 require_once "includes/boards.php";
				?>
			</div>	
			
		<?php endif; ?>
	
	<?php endif;?>

	<!-- Page generated -->
	<?php 
		$time_end = microtime(true);
		$time = $time_end - $time_start;
		printf("<p align=\"center\"><span class=\"generatedPage\">Page generated in: %1\$.2f sec.</span><br /></p>",$time);
	?>
	
	<div id="footer">
		<?php require_once("includes/footer.php"); ?>       
	</div>	
</div>
</body>
</html>
